package com.ants.listener;

import com.ants.model.TableModel;
import com.ants.utils.ExportUtils;
import com.ants.utils.JDBCUtils;
import org.apache.commons.lang3.StringUtils;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;

/**
 * @author 蚂蚁会花呗
 * @date 2021/11/3 14:25
 */
public class JFileChooserListener  {

    JTextField jFilePath;


    public JFileChooserListener() {

    }

    /**
     * 选择以及确定
     * @param jb1
     * @param labfilepath
     */
    public JFileChooserListener(JButton jb1,JButton jb2, JTextField labfilepath,JTextField jtf1,JTextField jtf2,JPasswordField jtf3) {
        //监听浏览按钮
        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setMultiSelectionEnabled(false);
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setDialogTitle("选择导出文件夹");
                int result = chooser.showOpenDialog(jb1);
                if (result == JFileChooser.APPROVE_OPTION) {
                    jFilePath = new JTextField();
                    File file = chooser.getSelectedFile();
                    String filepath = file.getAbsolutePath();
                    jFilePath.setText(filepath);
                    labfilepath.setText(filepath);
                }
            }
        });
        //监听确定按钮
        jb2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //导出
                List<TableModel> list = JDBCUtils.getResult(jtf1.getText(),jtf2.getText(),jtf3.getText());
                if (!list.isEmpty()){
                    try{
                        if (StringUtils.isBlank(jFilePath.getText())){
                            JOptionPane.showMessageDialog(jtf1,"请先选择路径！");
                        }else{
                            //导出excel
                            ExportUtils.export(list,jFilePath.getText());
                            //退出
                            System.exit(0);
                        }
                    }catch (Exception a){
                        JOptionPane.showMessageDialog(jtf1,"异常，请检查！");
                    }
                }else{
                    JOptionPane.showMessageDialog(jtf1,"数据库为空，请检查！");
                }
            }
        });

    }

}
